#include "rtsp_clients_manager.h"
#include <stdio.h>
#include <stdlib.h>
#include "rtsp_client.h"

struct RtspClientsManager
{
	int nr;
	int max_nr;
	struct RtspClient* rtsp_client[1];
};

static struct RtspClientsManager* M;

void rtsp_clients_manager_init(int max_nr)
{
	if(M != NULL){
		return;
	}

	M = (struct RtspClientsManager*)malloc(sizeof(struct RtspClientsManager) + sizeof(struct RtspClient*)*(max_nr + 1));
	M->max_nr = max_nr;
	M->nr = 0;

	return;
}

void rtsp_clients_manager_deinit(void)
{
    int i = 0;
    struct RtspClient* rtsp_client = NULL;
    
    if(M != NULL){
        for(i = 0; i < M->nr; i++){
            rtsp_client = M->rtsp_client[i];
            rtsp_client_destroy(rtsp_client);
        }
        free(M);
        M = NULL;
    }

    return;
}


int rtsp_clients_manager_get_count(void)
{
	if(M != NULL){
		return M->nr;	
	}
	
	return -1;
}
struct RtspClient* rtsp_clients_manager_get(int i)
{
	if(i >= 0 && M != NULL && i < M->max_nr){
		return M->rtsp_client[i];
	}

	return NULL;
}

int rtsp_clients_manager_add(struct RtspClient* rtsp_client)
{
	if(M == NULL ){
		return -1;
	}

	if(M->nr >= M->max_nr){
		return -1;
	}

	M->rtsp_client[M->nr++] = rtsp_client;

	return 0;
}

int rtsp_clients_manager_remove(struct RtspClient* rtsp_client)
{
	if(M== NULL ){
		return -1;
	}
	
	int i = 0;

	for(i = 0; i < M->nr; i++){
		if(M->rtsp_client[i] == rtsp_client){
			break;
		}
	}
	if(i < M->nr){
		for(;(i+1)< M->nr;i++){
			M->rtsp_client[i] = M->rtsp_client[i+1];
		}
		M->nr--;
		M->rtsp_client[M->nr] = NULL;
	}

	rtsp_client_destroy(rtsp_client);

	return 0;
}

